package com.qinggeng.project.common;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.utils.IdUtils;
import com.qinggeng.common.utils.sign.Base64;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.framework.web.domain.AjaxResult;

/**
 * 验证码操作处理
 * 
 * @author qinggeng
 */
@RestController
public class CaptchaController
{
    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response)
    {
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        try
        {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("uuid", uuid);
            ajax.put("img", generateCode2(verifyKey));
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 生成随机字符串验证码
     * @param verifyKey 存放Key
     * @return base64
     * @throws Exception
     */
    private String generateCode1(String verifyKey) throws Exception{
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            // png类型
            SpecCaptcha captcha = new SpecCaptcha(111, 36);
            captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
            redisCache.setCacheObject(verifyKey, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            captcha.out(stream);
            return Base64.encode(stream.toByteArray());
        }catch (Exception e){
            throw  e;
        }finally {
            stream.close();
        }
    }

    /**
     * 生成计算方法验证码
     * @param verifyKey 存放Key
     * @return base64
     * @throws Exception
     */
    private String generateCode2(String verifyKey) throws Exception{
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            // 算术类型 https://gitee.com/whvse/EasyCaptcha
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
            // 几位数运算，默认是两位
            captcha.setLen(2);
            // 获取运算的结果
            String result = captcha.text();
            redisCache.setCacheObject(verifyKey, result, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            captcha.out(stream);
            return Base64.encode(stream.toByteArray());
        }catch (Exception e){
            throw  e;
        }finally {
            stream.close();
        }

    }

}
